package com.sat.order.service.impl;

import com.sat.goods.feign.GoodsFeign;
import com.sat.goods.pojo.GoodsVo;
import com.sat.goods.pojo.Sku;
import com.sat.goods.pojo.Spu;
import com.sat.order.pojo.Cart;
import com.sat.order.pojo.OrderItem;
import com.sat.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GoodsFeign goodsFeign;

    @Override
    public void add(Integer num, Long skuid,String username) {

        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps("cart_" + username);

        Result<GoodsVo> result = goodsFeign.findById(skuid);
        GoodsVo goodsVo = result.getData();
        Sku sku = goodsVo.getSku();
        Spu spu = goodsVo.getSpu();

        OrderItem orderItem;

        if(boundHashOperations.get(skuid)==null){
            orderItem = new OrderItem();
            orderItem.setCategoryId2(spu.getCategory2Id());
            orderItem.setCategoryId3(spu.getCategory3Id());
            orderItem.setMoney(num*sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setNum(num);
            orderItem.setPrice(sku.getPrice());
            orderItem.setSkuId(skuid);
            orderItem.setSpuId(spu.getId());
            orderItem.setWeight(num*sku.getWeight());
            orderItem.setImage(sku.getImage());
            boundHashOperations.put(skuid,orderItem);
        }else{
            orderItem = (OrderItem) boundHashOperations.get(skuid);
            orderItem.setNum(orderItem.getNum()+num);
            boundHashOperations.put(skuid,orderItem);
        }
    }

    @Override
    public List<OrderItem> list(String username) {

        List<OrderItem> orderList = redisTemplate.boundHashOps("cart_" + username).values();
        return orderList;
    }

    @Override
    public void update(Integer num, Long skuid, String username) {
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps("cart_"+username);
        OrderItem orderItem = (OrderItem)boundHashOperations.get(skuid);
        orderItem.setNum(num);
        boundHashOperations.put(skuid,orderItem);
    }

    @Override
    public void delete(Long skuid,String username) {
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps("cart_"+username);
        boundHashOperations.delete(skuid);
    }

    @Override
    public void deleteAll(String username) {
        redisTemplate.delete("cart_"+username);
    }
}
